import React, { useEffect, useRef, useState, createRef, useImperativeHandle, useCallback, useMemo } from 'react';
import { connect, observer } from '@formily/react';
import { Carousel, Empty } from 'antd';
import Arrow from './arrow';
import { routerPrefix } from 'InbizConfig';
import { getImgList as getImgListData } from '../services';
import type { BannerProps } from '../index';
import { getEditor } from '@inbiz/utils';
import { useEvents } from '@inbiz/utils';
import { TextWidget } from '@inbiz/react';

const FocusView = (props: BannerProps) => {
  const {
    viewType,
    prefixCls = 'inbiz-Banner',
    imgCate,
    showImgTitle,
    displayNum,
    autoRoll,
    delay = 2,
    detail,
    imgWidth = 200,
    imgHeight = 150,
    refs
  } = props;
  const fixImgCate = useMemo(() => Array.isArray(imgCate) ? imgCate : imgCate ? [imgCate] : [], [imgCate]);
  const [imgList, setImgList] = useState<Banner.ImgItem[]>([]);
  const [wrapperStyle, setWrapperStyle] = useState<any>({});
  const [showNum, setShowNum] = useState(1);
  const [showList, setShowList] = useState<Banner.ImgItem[]>([]);
  const [instances, setInstances] = useState<any>([]);
  const [isInit, $init] = useState(false);
  const custom = useRef<boolean>(false)
  const wrapper = createRef<any>();
  const [configEvents] = useEvents(props.callBackEvents, props.emit)

  const getImgList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onParams?.(params)) || params;
    const data = await (configEvents.current?.onRequest || getImgListData)(newParams as any);
    return await configEvents.current?.onData?.(data) || data
  }, []);
  useEffect(() => {
    if (viewType === 'roll' && !displayNum || !fixImgCate?.length) {
      setImgList([])
      return
    }
    getImgList({
      categoryId: fixImgCate?.map((item: any) => item.id).toString(),
      pageIndex: 1,
      pageSize: 99999,
    }).then((res) => {
      // if (res.ContentList.length === 1 && viewType === 'focus') {
      //   setImgList([...res.ContentList, ...res.ContentList] || []);
      //   return;
      // }
      // if (viewType === 'roll' && res.ContentList.length <= 5) {
      //   setImgList([...res.ContentList, ...res.ContentList] || []);
      //   return;
      // }
      if (custom.current) return
      setImgList(res?.ContentList || []);
      $init(true)
    });
  }, [fixImgCate, viewType, displayNum]);

  const customData = (list: {
    ImgUrl: string;
    Title: string;
  }[]) => {
    custom.current = true
    setImgList(Array.isArray(list) ? list as any[] : []);
    $init(true)
  }

  useImperativeHandle(refs, () => ({
    customImageData: customData
  }), [])

  const gotoDetail = (record: any) => {
    const { ID, ImgLinkUrl } = record;
    const { origin, pathname, search } = window.location;
    if (getEditor() || !ID) return;

    if (!detail) {
      if (ImgLinkUrl && ImgLinkUrl !== 'isPureGraphMode') {
        window.open(ImgLinkUrl);
        return;
      }
    } else {
      const pageRoute = detail.split(',')[0];
      // 1./inbiz/web/editor/aok(设计器)  2./inbiz/web/aok(预览)
      window.open(
        `${origin}${pathname}${search}#${routerPrefix}${pageRoute}?imgId=${ID}`,
      );
    }
  };

  useEffect(() => {
    if (viewType === 'roll') {
      if (!displayNum) {
        if (imgList.length > 5) {
          setShowNum(5);
        } else {
          setShowNum(imgList.length);
        }
      } else {
        setShowNum(imgList.length < displayNum ? imgList.length : displayNum);
      }
    } else {
      setShowNum(1);
    }
  }, [displayNum, imgList, viewType]);

  useEffect(() => {
    if (
      (imgList.length === 1 && viewType === 'focus') ||
      (viewType === 'roll' && imgList.length <= 5)
    ) {
      setShowList([...imgList, ...imgList]);
    } else {
      setShowList(imgList);
    }
  }, [imgList, viewType]);

  useEffect(() => {
    if (wrapper.current) {
      setInstances(
        Array.from(
          wrapper.current.getElementsByClassName('img-item'),
          (i: any) => i,
        ),
      );
    }
  }, [imgList]);

  const beforeChange = (from: number, to: number) => {
    if (viewType === 'focus') {
      const ratio = instances[to]
        ? (instances[to].naturalHeight * instances[to].offsetWidth) /
        instances[to].naturalWidth
        : 300;
    }
  };

  return (
    <>
      {imgList?.length > 0 ? <div
        className={`${prefixCls}-wrapper ${prefixCls}-${viewType}`}
        ref={wrapper}
        style={{
          width: viewType == 'roll' ? showNum * (imgWidth + 16) + 48 || 'auto' : 'auto',
        }}
      >
        <Carousel
          key={imgList?.length}
          autoplay={autoRoll}
          autoplaySpeed={delay * 1000}
          slidesToShow={showNum ? showNum : showList.length > 5 ? 5 : showList.length}
          arrows={true}
          nextArrow={
            <Arrow
              viewType={viewType}
              length={imgList.length}
              type={viewType == 'roll' ? 'rollnext' : 'next'}
            />
          }
          prevArrow={
            <Arrow
              viewType={viewType}
              type={viewType == 'roll' ? 'rollprev' : 'prev'}
              direction={true}
              length={imgList.length}
            />
          }
          dots={false}
          infinite={true}
          effect={viewType === 'focus' ? 'fade' : 'scrollx'}
          beforeChange={beforeChange}
        >
          {showList.map((i, index) => (
            <div
              className={`${prefixCls}-content`}
              key={`${i.ID}_${index}`}
              onClick={() => gotoDetail(i)}
            >
              <img
                className={`img-item ${prefixCls}-content-img`}
                src={i.ImgUrl}
                style={{ height: viewType == 'roll' ? imgHeight : '', width: viewType == 'roll' ? imgWidth : '' }}
              />
              {showImgTitle && (
                <div
                  className={`${prefixCls}-content-title ${prefixCls}-${viewType}-title`}
                  style={{ fontSize: 'var(--inbiz-font-size-base)' }}
                >
                  <span>{i.Title}</span>
                </div>
              )}
            </div>
          ))}
        </Carousel>

      </div> : fixImgCate.length && !isInit ? null : <div style={{ padding: '16px' }}>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={<TextWidget>banner.noData</TextWidget>}
        />
      </div>}
    </>

  );
};

export default connect(FocusView);
